package server;

import org.dom4j.Attribute;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.List;

/**
 * @author: wudong
 * @create: 2021-07-27 13:43
 **/
public class Engine extends BaseContainer implements Lifecycle,RequestHandler {
    private String defaultHost;

    @Override
    public void init() throws Exception {
        Element element = getElement();
        Attribute name = element.attribute("name");
        setName(name.getValue());

        Attribute defaultHost = element.attribute("defaultHost");
        this.defaultHost = defaultHost.getValue();

        List hosts = element.selectNodes("Host");
        for (Object obj : hosts) {
            Element eleHost = (Element)obj;

            Host host = new Host();
            host.setElement(eleHost);
            host.setParent(this);

            host.init();
            addChild(host);
        }
    }

    @Override
    public void start() throws Exception {
        Container[] children = findChildren();
        for (Container child : children) {
            child.start();
        }
    }

    @Override
    public void invoke(Request request, Response response) throws Exception {
        String hostUrl = request.getHost();
        HashMap<String, Container> children = this.children;
        Host host = (Host)children.get(hostUrl);
        if(host == null){
            host = (Host)children.get(defaultHost);
        }
        if(host == null){
            response.output(HttpProtocolUtil.getHttpHeader404());
        }else {
            host.invoke(request,response);
        }
    }
}
